import datetime
import time
import logging
import os


def get_current_time():
    # current_time = time.strftime('%Y-%m/%d', time.localtime(time.time()))  # 返回当前时间
    timeObj = datetime.datetime.now()
    current_time = timeObj.strftime('%Y-%m/%d-') + ('am' if timeObj.hour <= 12 else 'pm')
    return current_time


class Logger(object):
    count = 0

    def __init__(self, fmt='%(asctime)s [%(pathname)s] 行号:%(lineno)d %(levelname)s: %(message)s'):
        # current_directory = os.path.dirname(os.path.abspath(__file__))
        # print(current_directory)
        # self.log_dir_path = os.path.abspath(os.path.dirname(current_directory) + os.path.sep + "logs")
        # self.log_dir_path = os.path.abspath(os.path.dirname('./') + os.path.sep + "logs")
        self.log_dir_path = os.path.abspath('./logs/')
        print(self.log_dir_path)
        if not os.path.exists(self.log_dir_path):
            os.makedirs(self.log_dir_path)
        self.current_time = get_current_time()
        self.logger = logging.getLogger()
        self.format_str = logging.Formatter(fmt)  # 设置日志格式
        self.create_handler(self.current_time)
        Logger.count += 1

    def create_handler(self, current_time):
        self.logger.setLevel(logging.DEBUG)
        filename = self.log_dir_path + '/' + current_time + '.log'
        if not os.path.exists(os.path.dirname(filename)):
            os.makedirs(os.path.dirname(filename))
        th = logging.FileHandler(filename=filename, encoding='utf-8')
        th.setFormatter(self.format_str)  # 设置文件里写入的格式
        sh = logging.StreamHandler()  # 往屏幕上输出
        sh.setFormatter(self.format_str)  # 设置屏幕上显示的格式
        if self.logger.handlers:
            self.logger.handlers.clear()
        self.logger.addHandler(sh)  # 把对象加到logger里
        self.logger.addHandler(th)
        self.current_time = current_time

    def debug(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler(current_time)
        self.logger.debug(msg)
        return

    def info(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler(current_time)

        self.logger.info(msg)
        # self.logger.removeHandler(self.logger.handlers)
        # cls.log.info(msg)
        return

    def warning(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler(current_time)
        self.logger.warning(msg)
        return

    def error(self, msg):
        current_time = get_current_time()
        if self.current_time != current_time:
            self.create_handler(current_time)
        self.logger.error(msg)
        return


logger = Logger()

if __name__ == '__main__':
    log = Logger()
    log.logger.debug('debug')
    log.info('info')
    time.sleep(2)
    log.info('info')
    log.info('info')
    log.logger.warning('警告')
    log.logger.error('报错')
    log.logger.critical('严重')
    Logger().logger.error('error')
